const http = require('http');
const Koa = require('koa');
const Router = require('koa-router');
const cors = require('koa-cors');
const json = require('koa-json');
const bodyParse = require('co-body');
const serve = require('koa-static');
const logger = require('koa-logger');
const compress = require('koa-compress');
const onerror = require('koa-onerror');
const favicon = require('koa-favicon');
const convert = require('koa-convert');

const db = require('./config/mongoose')();
db.on('error', console.error.bind(console, 'error: connect error!'))
db.once('open', function () {
  // 一次打开记录
  console.log('connect success!')
})

const app = new Koa();
app.use(favicon(`${__dirname}/public/favicon.ico`));

onerror(app);

app.use(async (ctx, next) => {
  await next();
  ctx.set('X-Powered-By', 'Koa2');
});

app.use(compress({
  threshold: 2048,
  flush: require('zlib').Z_SYNC_FLUSH
}));

app.use(convert(logger()));
app.use(convert(cors()));
app.use(convert(json()));

app.use(convert(serve(__dirname + '/public/')));

const port = process.env.PORT || 3000;

http.createServer(app.callback()).listen(port, () => {
  console.log(`Server up and running! On port  ${port} !`);
});

